package client

import (
	"feng-che.com/server/driver-quiz/internal/constants"
	serverCommon "fiberCommonUtils/common"
	"fmt"
	"github.com/gofiber/fiber/v2"
	"github.com/yeqown/go-qrcode/v2"
	"github.com/yeqown/go-qrcode/writer/standard"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"os"
	"time"
)

func GenerateClientQrcode(c *fiber.Ctx) error {
	cid := c.Locals("ClientID").(primitive.ObjectID)
	qrc, err := qrcode.New(cid.Hex())
	if err != nil {
		fmt.Printf("could not generate QRCode: %v", err)
		return fiber.NewError(500, fmt.Sprint("could not generate QRCode:", err.Error()))
	}
	opts := standard.WithQRWidth(uint8(int(6)))
	fileName := constants.GetQrcodeDirPath() + cid.Hex() + ".png"
	writer, err := standard.New(fileName, opts)
	if err != nil {
		return fiber.NewError(500, fmt.Sprint("写入文件失败,", err.Error()))
	}
	err = qrc.Save(writer)
	if err != nil {
		return fiber.NewError(500, fmt.Sprint("写入文件失败,", err.Error()))
	}
	file, err := os.ReadFile(fileName)
	if err != nil {
		return fiber.NewError(500, fmt.Sprint("读取qrcode文件失败,", err.Error()))
	}
	go func() {
		time.Sleep(30 * time.Second)
		errRm := os.Remove(fileName)
		if errRm != nil {
			fmt.Println("删除qrcode文件失败,", errRm.Error())
		}
	}()
	return c.JSON(serverCommon.MakeSuccessJson(file))
}
